# coding: utf-8

# -------------------------------------------------------------------------------
# Name:         api.py
# Description:  
# Author:       XiangjunZhao
# EMAIL:        2419352654@qq.com
# Date:         2019/11/18 17:32
# -------------------------------------------------------------------------------
from rest_framework import serializers

from apps.HttpAutoTestService.serializers import BaseListSerializer, BaseSerializer
from apps.HttpAutoTestService.models import Api, Testcase
from apps.HttpAutoTestService.serializers import TidyProjectSerializer, TidyModuleSerializer, TidyEnvironmentSerializer

__all__ = ['ApiNameListSerializer', 'ApiListSerializer', 'ApiSerializer', 'TidyApiSerializer']


class ApiNameListSerializer(serializers.ModelSerializer):
    environment = serializers.CharField(read_only=True)

    class Meta:
        model = Api
        fields = ('id', 'name', 'url', 'method', 'request_params', 'headers', 'request_data', 'request_data_type',
                  'environment')


class ApiListSerializer(BaseListSerializer):
    project = TidyProjectSerializer()
    module = TidyModuleSerializer()
    environment = TidyEnvironmentSerializer()
    status = serializers.SerializerMethodField()

    def get_status(self, obj):
        pass_total = Testcase.objects.filter(api=obj.id, status='PASS', is_deleted=False).count()
        total = Testcase.objects.filter(api=obj.id, is_deleted=False).count()
        return "{pass_total} / {total}".format(pass_total=pass_total, total=total)

    class Meta:
        model = Api
        fields = '__all__'


class ApiSerializer(BaseSerializer):
    class Meta:
        model = Api
        fields = '__all__'
        extra_kwargs = {
            'project': {'required': True},
            'module': {'required': True},
        }


class TidyApiSerializer(serializers.ModelSerializer):
    project = TidyProjectSerializer()

    class Meta:
        model = Api
        fields = ('id', 'name', 'url', 'project', 'is_deleted')
